// 正则表达式测试工具
class RegexTester {
    static commonPatterns = {
        '邮箱': /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
        '手机号': /^1[3-9]\d{9}$/,
        'URL': /^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/,
        'IPv4地址': /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
        '身份证号': /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
        '中文字符': /^[\u4e00-\u9fa5]+$/,
        '英文字母': /^[a-zA-Z]+$/,
        '数字': /^\d+$/,
        '日期(YYYY-MM-DD)': /^\d{4}-\d{2}-\d{2}$/,
        '时间(HH:MM:SS)': /^([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$/,
        '密码强度(8位+大小写+数字)': /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d@$!%*?&]{8,}$/,
        'HTML标签': /<\/?[a-z][\s\S]*>/i
    };

    static testRegex(pattern, flags, testString, options = {}) {
        try {
            if (!pattern) {
                return { success: false, error: '正则表达式不能为空' };
            }

            if (!testString && testString !== '') {
                return { success: false, error: '测试文本不能为空' };
            }

            // 创建正则表达式对象
            const regex = new RegExp(pattern, flags);
            
            // 执行测试
            const isMatch = regex.test(testString);
            
            // 获取匹配结果
            const matches = this.getMatches(regex, testString, flags);
            
            // 计算统计信息
            const stats = this.calculateStats(regex, testString, matches);
            
            return {
                success: true,
                data: {
                    isMatch,
                    matches,
                    stats,
                    regex: {
                        source: regex.source,
                        flags: regex.flags,
                        global: regex.global,
                        ignoreCase: regex.ignoreCase,
                        multiline: regex.multiline,
                        sticky: regex.sticky,
                        unicode: regex.unicode,
                        dotAll: regex.dotAll
                    }
                }
            };
        } catch (error) {
            return { success: false, error: `正则表达式错误: ${error.message}` };
        }
    }

    static getMatches(regex, testString, flags) {
        const matches = [];
        
        if (flags && flags.includes('g')) {
            // 全局匹配
            let match;
            const globalRegex = new RegExp(regex.source, flags);
            while ((match = globalRegex.exec(testString)) !== null) {
                matches.push({
                    match: match[0],
                    index: match.index,
                    groups: match.slice(1),
                    namedGroups: match.groups || {},
                    input: match.input,
                    length: match[0].length
                });
                
                // 防止无限循环
                if (match[0].length === 0) {
                    globalRegex.lastIndex++;
                }
            }
        } else {
            // 单次匹配
            const match = testString.match(regex);
            if (match) {
                matches.push({
                    match: match[0],
                    index: match.index,
                    groups: match.slice(1),
                    namedGroups: match.groups || {},
                    input: match.input,
                    length: match[0].length
                });
            }
        }
        
        return matches;
    }

    static calculateStats(regex, testString, matches) {
        return {
            totalMatches: matches.length,
            hasMatch: matches.length > 0,
            testStringLength: testString.length,
            regexPattern: regex.source,
            regexFlags: regex.flags,
            matchedLength: matches.reduce((sum, match) => sum + match.length, 0),
            coverage: testString.length > 0 ? 
                (matches.reduce((sum, match) => sum + match.length, 0) / testString.length * 100).toFixed(2) + '%' : '0%'
        };
    }

    static replaceWithRegex(pattern, flags, testString, replacement) {
        try {
            if (!pattern) {
                return { success: false, error: '正则表达式不能为空' };
            }

            if (!testString && testString !== '') {
                return { success: false, error: '测试文本不能为空' };
            }

            if (replacement === undefined || replacement === null) {
                replacement = '';
            }

            const regex = new RegExp(pattern, flags);
            const result = testString.replace(regex, replacement);
            
            // 计算替换统计
            const originalMatches = this.getMatches(regex, testString, flags);
            const replacedMatches = this.getMatches(regex, result, flags);
            
            return {
                success: true,
                data: {
                    original: testString,
                    result: result,
                    replacementCount: originalMatches.length - replacedMatches.length,
                    originalMatches: originalMatches,
                    hasChanges: testString !== result
                }
            };
        } catch (error) {
            return { success: false, error: `替换操作错误: ${error.message}` };
        }
    }

    static validatePattern(pattern) {
        try {
            if (!pattern) {
                return { success: false, error: '正则表达式不能为空' };
            }
            
            new RegExp(pattern);
            return { success: true, data: { valid: true } };
        } catch (error) {
            return { 
                success: false, 
                error: error.message,
                data: { valid: false, errorMessage: error.message }
            };
        }
    }

    static getCommonPatterns() {
        return {
            success: true,
            data: Object.entries(this.commonPatterns).map(([name, pattern]) => ({
                name,
                pattern: pattern.source,
                flags: pattern.flags,
                description: this.getPatternDescription(name)
            }))
        };
    }

    static getPatternDescription(name) {
        const descriptions = {
            '邮箱': '匹配标准邮箱格式，如：user@example.com',
            '手机号': '匹配中国大陆手机号码格式',
            'URL': '匹配HTTP/HTTPS网址',
            'IPv4地址': '匹配IPv4地址格式',
            '身份证号': '匹配中国大陆18位身份证号码',
            '中文字符': '匹配中文汉字',
            '英文字母': '匹配英文字母（大小写）',
            '数字': '匹配纯数字',
            '日期(YYYY-MM-DD)': '匹配年-月-日格式的日期',
            '时间(HH:MM:SS)': '匹配时:分:秒格式的时间',
            '密码强度(8位+大小写+数字)': '匹配包含大小写字母和数字的8位以上密码',
            'HTML标签': '匹配HTML标签'
        };
        return descriptions[name] || '';
    }

    static explainRegex(pattern) {
        try {
            if (!pattern) {
                return { success: false, error: '正则表达式不能为空' };
            }

            // 简单的正则解释
            const explanations = [];
            let pos = 0;
            
            while (pos < pattern.length) {
                const char = pattern[pos];
                
                switch (char) {
                    case '^':
                        explanations.push({ symbol: '^', meaning: '行的开始', position: pos });
                        break;
                    case '$':
                        explanations.push({ symbol: '$', meaning: '行的结束', position: pos });
                        break;
                    case '.':
                        explanations.push({ symbol: '.', meaning: '匹配任意字符（除换行符）', position: pos });
                        break;
                    case '*':
                        explanations.push({ symbol: '*', meaning: '匹配前面的字符0次或多次', position: pos });
                        break;
                    case '+':
                        explanations.push({ symbol: '+', meaning: '匹配前面的字符1次或多次', position: pos });
                        break;
                    case '?':
                        explanations.push({ symbol: '?', meaning: '匹配前面的字符0次或1次', position: pos });
                        break;
                    case '\\':
                        if (pos + 1 < pattern.length) {
                            const nextChar = pattern[pos + 1];
                            const escaped = '\\' + nextChar;
                            explanations.push({ 
                                symbol: escaped, 
                                meaning: this.getEscapedMeaning(nextChar), 
                                position: pos 
                            });
                            pos++;
                        }
                        break;
                    case '[':
                        const endBracket = pattern.indexOf(']', pos);
                        if (endBracket !== -1) {
                            const charClass = pattern.substring(pos, endBracket + 1);
                            explanations.push({ 
                                symbol: charClass, 
                                meaning: '字符类：匹配方括号内的任意字符', 
                                position: pos 
                            });
                            pos = endBracket;
                        }
                        break;
                    case '(':
                        explanations.push({ symbol: '(', meaning: '分组开始', position: pos });
                        break;
                    case ')':
                        explanations.push({ symbol: ')', meaning: '分组结束', position: pos });
                        break;
                    case '|':
                        explanations.push({ symbol: '|', meaning: '或操作符', position: pos });
                        break;
                    case '{':
                        const endBrace = pattern.indexOf('}', pos);
                        if (endBrace !== -1) {
                            const quantifier = pattern.substring(pos, endBrace + 1);
                            explanations.push({ 
                                symbol: quantifier, 
                                meaning: '量词：指定重复次数', 
                                position: pos 
                            });
                            pos = endBrace;
                        }
                        break;
                }
                pos++;
            }

            return {
                success: true,
                data: {
                    pattern: pattern,
                    explanations: explanations,
                    summary: `该正则表达式包含 ${explanations.length} 个特殊元素`
                }
            };
        } catch (error) {
            return { success: false, error: `解释正则表达式时出错: ${error.message}` };
        }
    }

    static getEscapedMeaning(char) {
        const meanings = {
            'd': '匹配数字字符 (0-9)',
            'D': '匹配非数字字符',
            'w': '匹配单词字符 (字母、数字、下划线)',
            'W': '匹配非单词字符',
            's': '匹配空白字符 (空格、制表符等)',
            'S': '匹配非空白字符',
            'n': '匹配换行符',
            'r': '匹配回车符',
            't': '匹配制表符',
            'b': '匹配单词边界',
            'B': '匹配非单词边界'
        };
        return meanings[char] || `转义字符 \\${char}`;
    }
}